<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="账号信息"></u-navbar> -->
		<free-list-item title="我的头像" :showRight="false" :showLeftIcon="false" @click="uploadAvatar">
			<u-image slot="right" :src="user.avatar" border-radius="100rpx"
				style="width: 60px; height: 60px;  margin-right: 10px;" @error="handleImageError"></u-image>
		</free-list-item>
		<free-list-item title="名字" :showRight="false" :showRightIcons="false" :showLeftIcon="false">
			<text slot="right" class="font-14 text-muted">{{user.username}}</text>
		</free-list-item>
		<free-list-item title="绑定手机号" :showRight="false" :showLeftIcon="false" @click="getPhone()">
			<text slot="right" class="font-14 text-muted ursrRight">{{user.phone}}</text>
		</free-list-item>

		<free-list-item title="登录密码" :showRight="false" :showLeftIcon="false" @click="editPassword()">
			<text slot="right" class="font-14 text-muted ursrRight">*********</text>
		</free-list-item>
		<!-- 修改名字|修改微信号 弹框-->
		<free-confirm ref="confirm" :title="confirmTitle">
			<view class="pl-3">
				<u-form :model="form" ref="uForm">
					<u-form-item :required="true" label="原密码" label-width="120" prop="oldPassword">
						<u-input class="mr-3 " :password-icon="true" type="password" placeholder="请输入原密码" v-model="form.oldPassword" input-align="right" />
					</u-form-item>
					<u-form-item :required="true" label="新密码" label-width="120" prop="newPassword">
						<u-input class="mr-3 " :password-icon="true" type="password" placeholder="请输入新密码" v-model="form.newPassword" input-align="right" />
					</u-form-item>
					<u-form-item :required="true" label="确认新密码" label-width="180" prop="confirmPassword">
						<u-input class="mr-3 " :password-icon="true" type="password" placeholder="请再次输入密码" v-model="form.confirmPassword" input-align="right" />
					</u-form-item>
				</u-form>
					<view class="font-12 mt-1" style="color: red;">由英文、数字、特殊字符中的至少2种组成，不少于6位</view>
			</view>
		</free-confirm>
		<!-- 修改手机号码 弹框-->
		<free-confirm ref="confirmShow" :title="confirmPhomTitle">
			<view class="pl-3">
				<u-form>
					<u-form-item :required="true" label="手机号码" label-width="150" prop="phone">
						<u-input class="mr-3 " placeholder="请输入所绑定的手机号" v-model="code.phone" input-align="right" />
					</u-form-item>
					<u-form-item :required="true" label="验证码" label-width="150" prop="captcha">
						<u-input class="mr-3 " placeholder="请输入验证码" v-model="code.captcha" input-align="right" />
						<u-button size="mini" slot="right" type="warning" @click="getCode">{{codeText}}</u-button>
					</u-form-item>
					<u-toast ref="uToast"></u-toast>
					<u-verification-code :seconds="seconds" @end="end" @start="start" ref="uCode"
						@change="codeChange"></u-verification-code>
				</u-form>
			</view>
		</free-confirm>
	</view>
</template>

<script>
	import freeListItem from "@/components/free-ui/free-list-item.vue";
	import freeAvater from "@/components/free-ui/free-avater.vue";
	import freeDivider from "@/components/free-ui/free-divider.vue";
	import freeConfirm from "@/components/free-ui/free-confirm.vue";
	import $H from '@/common/free-lib/request.js';
	import $U from "@/common/free-lib/util.js";

	export default {
		components: {
			freeListItem,
			freeAvater,
			freeDivider,
			freeConfirm
		},
		data() {
			return {
				user: {
					avatar: "",
				    username: $U.getStorage("username"),
					phone: $U.getStorage('phone')
				},
				form: {
					oldPassword: '', // 原密码
					newPassword: '', // 新密码
					confirmPassword: '', // 确认密码
				},
				codeText: '',
				
				code: {
					phone: '',
					captcha: ''
				},
				seconds: 60,
				rules: {
					oldPassword: [{
							required: true,
							message: '原密码不能为空',
							trigger: ['change', 'blur'],
						},
						{
						    validator: (rule, value, callback) => {
						        // 正则表达式，要求密码包含英文、数字、特殊字符中的至少2种组成，不少于6位
						        const reg = /^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[A-Za-z\d\W_]{6,}$/;
						        if (!reg.test(value)) {
						            callback(new Error('密码必须包含英文、数字、特殊字符中的至少二种，且长度不少于6位'));
						        } else {
						            callback();
						        }
						    },
						    trigger: ['change', 'blur'],
						}
					],

					newPassword: [{
							required: true,
							message: '新密码不能为空',
							trigger: ['change', 'blur'],
						},
						{
						    validator: (rule, value, callback) => {
						        // 正则表达式，要求密码包含英文、数字、特殊字符中的至少2种组成，不少于6位
						        const reg = /^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[A-Za-z\d\W_]{6,}$/;
						        if (!reg.test(value)) {
						            callback(new Error('密码必须包含英文、数字、特殊字符中的至少二种，且长度不少于6位'));
						        } else {
						            callback();
						        }
						    },
						    trigger: ['change', 'blur'],
						}
					],
					confirmPassword: [{
							required: true,
							message: '确认新密码不能为空',
							trigger: ['change', 'blur'],
						},
						{
						    validator: (rule, value, callback) => {
						        // 正则表达式，要求密码包含英文、数字、特殊字符中的至少2种组成，不少于6位
						        const reg = /^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[A-Za-z\d\W_]{6,}$/;
						        if (!reg.test(value)) {
						            callback(new Error('密码必须包含英文、数字、特殊字符中的至少二种，且长度不少于6位'));
						        } else {
						            callback();
						        }
						    },
						    trigger: ['change', 'blur'],
						}
					],
				},
			}
		},
		computed: {
			confirmTitle() {
				return this.confirmType == 'username' ? '修改密码' : '修改密码'
			},
			confirmPhomTitle() {
				return this.confirmType == 'username' ? '更换手机号' : '更换手机号'
			},
			placeholder() {
				return this.confirmType == 'username' ? '输入账号' : '输入名称'
			},

		},

		onLoad(options) {
			let avatar = $U.getStorage('avatar');
			let phone = $U.getStorage('phone');
			if (avatar) {
				this.user.avatar = $H.getFullImageUrl(avatar);
			} else {
				this.user.avatar = "../../../static/logo.png";
			}
		},


		methods: {
			handleImageError() {
				uni.showToast({
					title: '图片格式不支持jpeg，请重新上传',
					icon: 'none',
					duration: 4000
				});

			},
			editPassword() {
				const that = this;
				const userId = $U.getStorage('id');
				if (!userId) {
					uni.showToast({
						title: '请重新登录',
						icon: 'error'
					})
					return;
				}

				this.$refs.confirm.show((close) => {
					if (!that.form.oldPassword || !that.form.newPassword || !that.form.confirmPassword) {
						uni.showToast({
							title: "请填写正确密码",
							icon: 'none'
						})
						return;
					}

					if (that.newPassword != that.confirmPassword) {
						uni.showToast({
							title: "两次密码不一致",
							icon: 'none'
						})
						return;
					}
					uni.showLoading({
						title: '加载中'
					});
					$H.post('/brand/user/upper/editPassword?id=' + userId + "&newPassword=" + that.form.newPassword +
						"&confirmPassword=" + that.form.confirmPassword + "&oldPassword=" + that.form.oldPassword, {

						}).then(res => {
						uni.hideLoading();
						if (!res.success) {
							uni.showToast({
								title: res.message || '修改失败',
								icon: 'error'
							});
							return
						}
						uni.showToast({
							title: '修改成功',
							icon: 'success'
						});
					}).catch(error => {
						console.log(error)
						uni.hideLoading();
					})
					close()
				})
			},
			// 绑定手机

			codeChange(text) {
				this.codeText = text;
			},

			validatePhoneNumber(phoneNumber) {
				var regex = /^1\d{10}$/;
				return regex.test(phoneNumber);
			},

			getCode() {
				if (this.getCodeisWaiting) {
					return;
				}
				if (!this.code.phone) {
					uni.showToast({
						title: "请输入手机号",
						icon: 'none'
					});
					return;
				}
				uni.hideKeyboard();
				this.getCodeText = "发送中...";
				this.getCodeisWaiting = true;
				let o = {
					phone: this.code.phone
				};
				$H.post('/brand/user/upper/editePhoneSendSms', o, {
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
						}
					})
					.then(res => {
						if (!res.success || res.code != 200) {
							uni.showToast({
								title: res.message || '获取验证码失败',
								icon: 'error'
							});
							return;
						}

						if (this.$refs.uCode.canGetCode) {
							if (!this.validatePhoneNumber(this.code.phone)) {
								uni.showToast({
									title: "手机号码格式错误",
									icon: "error"
								});
								return;
							}
							uni.showLoading({
								title: '正在获取验证码'
							});
							setTimeout(() => {
								this.$refs.uCode.start();
							}, 2000);
						} else {
							this.$u.toast('倒计时结束后再发送');
							this.getCodeisWaiting = false
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none'
						});
					});
			},
			end() {
				this.$u.toast('倒计时结束');
				this.getCodeisWaiting = false;
				this.codeText = '重新获取';
			},
			start() {
				this.$u.toast('倒计时开始');
			},




			editePhone() {
				const userId = $U.getStorage('id');
				if (!userId) {
					uni.showToast({
						title: '请重新登录',
						icon: 'error'
					})
					return;
				}

				let o = {
					...this.code,
					id: userId
				};
				$H.post('/brand/user/upper/editePhone', o, {
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
						}
					})
					.then(res => {
						if (res.code === 200) {
							uni.showToast({
								title: res.message,
								icon: 'none',
							});
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
							});
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none'
						});
					});
			},
			/**end  验证码**/

			getPhone() {
				this.$refs.confirmShow.show((close) => {
					if (!this.code.phone) {
						uni.showToast({
							title: "请输入手机号",
							icon: 'none'
						});
						return;
					}

					if (!this.captcha) {
						uni.showToast({
							title: "请输入验证码",
							icon: 'none'
						});
						return;
					}
					this.editePhone();
					close();
				});
			},

			uploadAvatar() {
				const that = this;

				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					success: (res) => {
						uni.showLoading({
							title: '加载中'
						});
						// 上传
						$H.upload("/sys/common/upload", {
							filePath: res.tempFiles[0].path,
							name: 'file',
							formData: {
								"biz": "temp"
							}
						}).then(res => {
							uni.hideLoading();
							const path = res.message;
							that.updateAvatar(path);
						}).catch(error => {
							uni.hideLoading();
							console.log(error)
						});
					}
				})

			},
			updateAvatar(path) {
				const that = this;
				const userId = $U.getStorage('id');
				if (!userId) {
					uni.showToast({
						title: '请重新登录',
						icon: 'error'
					})
					return;
				}

				uni.showLoading({
					title: '加载中'
				});
				$H.post('/brand/user/upper/editAvatar?id=' + userId + "&avatar=" + path, {

				}).then(res => {
					uni.hideLoading();
					if (!res.success) {
						uni.showToast({
							title: res.message || '修改失败',
							icon: 'error'
						});
						return
					}
					uni.showToast({
						title: '修改成功',
						icon: 'success'
					});
					$U.setStorage('avatar', path);
					that.user.avatar = $H.getFullImageUrl(path)
				}).catch(error => {
					console.log(error)
					uni.hideLoading();
				})
			},
			openCode() {
				uni.navigateTo({
					url: '/pages/my/code/code'
				})
			}
		}
	}
</script>

<style>
</style>